package com.yh.csx.bsf.cat;

import com.fasterxml.jackson.core.type.TypeReference;
import com.yh.csx.bsf.core.thread.ThreadPool;
import com.yh.csx.bsf.core.util.*;
import redis.clients.jedis.JedisCluster;

import java.util.HashMap;

/**
 * @author: chejiangyi
 * @version: 2019-08-14 11:01
 **/
public class RateLimiterCatRedisProvider {
    private boolean isClose = true;

    public void start() {
        isClose = false;
        ThreadPool.System.submit("bsf系统任务:缓存流控阈值", () -> {
            while (!ThreadPool.System.isShutdown() && !isClose) {
                try {
                    run();
                } catch (Exception e) {
                    LogUtils.error(RateLimiterCatRedisProvider.class, CatRateLimiter.Project, "run->循环缓存流控阈值出错", e);
                }
                try {
                    Thread.sleep(PropertyUtils.getPropertyCache(CatProperties.RateLimiterRedisTimes, 60000));
                } catch (Exception e) {
                }
            }
        });
    }

    public void run() {
        if(PropertyUtils.getPropertyCache(CatProperties.RateLimiterEnabled,false)){
            JedisCluster jedisCluster=ContextUtils.getBean(JedisCluster.class, false);
            if(jedisCluster!=null){
                String json=jedisCluster.get(CatRateLimiter.Project+"-"+CatProperties.getRateLimiterCatName());
                if(!StringUtils.isEmpty(json)){
                    HashMap<String,Double> jsonObject = JsonUtils.deserialize(json, new TypeReference<HashMap<String,Double>>(){}.getType());
                    CatRateLimiter.updateResourceQpsAll(jsonObject);
                }
            }
        }
    }
    public void close() {
        isClose=true;
    }

}
